import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Product, ProductService, Comment} from '../shared/product.service';
import {WebSocketService} from '../shared/web-socket.service';
import {Subscription} from 'rxjs';

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {
  product: Product;

  comments: Comment[];
  // 最新的评论和星级
  public newRating = 5;
  public newComment = '';
  // 设置发表评论模块是否隐藏
  public isCommentHidden = true;
  public isWatched = false;
  public currentBid: number;
  subscription: Subscription;

  constructor(private routeInfo: ActivatedRoute, private productService: ProductService, private wsService: WebSocketService) {
  }

  ngOnInit() {
    const productId: number = this.routeInfo.snapshot.params.prodId;
    this.productService.getProduct(productId).subscribe(
      data => {
        this.product = data;
        this.currentBid = this.product.price;
      }
    );
    this.productService.getCommentsForProductId(productId).subscribe(
      comments => {
        this.comments = comments;
      }
    );
  }

  addComment() {
    const newComment = new Comment(this.comments.length + 1, this.product.id, new Date().toISOString(),
      '丁春秋', this.newRating, this.newComment);
    this.comments.unshift(newComment);
    const totalStars = this.comments.reduce((sum, comment) => sum + comment.rating, 0);
    this.product.rating = totalStars / this.comments.length;
    this.isCommentHidden = !this.isCommentHidden;
    this.newRating = 5;
    this.newComment = '';
  }

  watchProduct() {
    if (this.subscription) {
      this.subscription.unsubscribe();
      this.isWatched = false;
      this.subscription = null;
    } else {
      this.isWatched = true;
      this.subscription = this.wsService.createObservableSocket('ws://localhost:8085', this.product.id).subscribe(
        productIds => {
          const product = productIds.find(p => p.productId === this.product.id);
          this.currentBid = product.bid;
        }
      );
    }
  }
}
